import axios, { AxiosResponse, AxiosInstance, InternalAxiosRequestConfig } from "axios";
import Loading from '@/components/loading'
import { createRoot } from 'react-dom/client'

const instance: AxiosInstance = axios.create({
    baseURL: import.meta.env.VITE_BASE_URL,
    timeout: 80000
})

instance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
    const dom = document.createElement('div')
    dom.setAttribute('id', 'loading')
    document.body.appendChild(dom)
    if(dom){
        createRoot(document.getElementById('loading')!).render(<Loading />)
    }
    return config
})

instance.interceptors.response.use(
    (response: AxiosResponse) => {
        document.body.removeChild(document.getElementById('loading')!)
        return response.data
    }, (error) => {
        document.body.removeChild(document.getElementById('loading')!)
        console.log(error);

    }
)

export default instance